package com.hxzy.common.exsyexcel;

import com.alibaba.excel.converters.Converter;
import com.alibaba.excel.metadata.GlobalConfiguration;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.metadata.property.ExcelContentProperty;
import org.springframework.web.client.RestTemplate;

import java.io.IOException;

/**
 * 自定义图片的转换器
 */
public class ImageConvert implements Converter<String> {

    @Override
    public Class<?> supportJavaTypeKey() {
        return String.class;
    }


    /**
     * 把转换后的结果写入到excel单元格中
     * @param value
     * @param contentProperty
     * @param globalConfiguration
     * @return
     * @throws IOException
     */
    @Override
    public WriteCellData<?> convertToExcelData(String value, ExcelContentProperty contentProperty, GlobalConfiguration globalConfiguration) throws IOException {
        //value  =https://waimai-1300180953.cos.ap-chongqing.myqcloud.com/images/d315ccf5-c0f9-4169-8056-33e64dcbd0b9.png

        //1、创建一个http请求对象 (spring 框架封装的)
        RestTemplate  restTemplate=new RestTemplate();
        try {
            byte[] forObject = restTemplate.getForObject(value, byte[].class);
            return new WriteCellData<>(  forObject  );
        }catch (Exception e){
            return new WriteCellData<>("图片下载失败");
        }

        //return new WriteCellData(FileUtils.readFileToByteArray(new File(value)));
    }

}
